<?php

namespace App\Http\Middleware;

use App\Models\DawnZhjyUser;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Models\DawnUser;

class HttpLoggingMiddleware
{
    private $startTime;

    public function handle(Request $request, Closure $next)
    {
        // 记录开始时间
        $this->startTime = microtime(true);
        
        // 记录请求信息
        $this->logRequest($request);

        $response = $next($request);

        // 记录响应信息，包括处理时间
        $this->logResponse($response);

        return $response;
    }

    private function logRequest(Request $request)
    {
        $method = $request->method();
        $url = $request->fullUrl();
        $headers = $request->headers->all();
        $body = $request->getContent();
        $userAgent = $request->header('User-Agent');
        $requestTime = now()->format('Y-m-d H:i:s');
        
        // 获取用户信息
        $userInfo = "未登录用户";
        try {
            // 检查会话是否可用
            if ($request->hasSession()) {
                $sessionData = $request->session()->all();
                // 从会话中获取用户ID
                foreach ($sessionData as $key => $value) {
                    if (strpos($key, 'login_web_') === 0) {
                        $userId = $value;
                        $userInfo = "用户ID: " . $userId;
                        
                        // 获取更多用户信息
                        $zhjyUser = DawnZhjyUser::where('dawn_id', $userId)->first();
                        if ($zhjyUser) {
                            if (isset($zhjyUser->dawn_zhjyIdName)) {
                                $userInfo .= ", 姓名: " . $zhjyUser->dawn_zhjyIdName;
                            }
                            if (isset($zhjyUser->dawn_zhjyCreateTime)) {
                                $userInfo .= ", 注册时间: " . $zhjyUser->dawn_zhjyCreateTime;
                            }
                            if (isset($zhjyUser->dawn_zhjyStatus)) {
                                $statusMap = ['0' => '正常', '1' => '禁用'];
                                $userInfo .= ", 状态: " . ($statusMap[$zhjyUser->dawn_zhjyStatus] ?? $zhjyUser->dawn_zhjyStatus);
                            }
                            if (isset($zhjyUser->dawn_zhjyType)) {
                                $typeMap = ['1' => '普通用户', '2' => '管理员'];
                                $userInfo .= ", 类型: " . ($typeMap[$zhjyUser->dawn_zhjyType] ?? $zhjyUser->dawn_zhjyType);
                            }
                            if (isset($zhjyUser->dawn_zhjyLastLoginTime)) {
                                $userInfo .= ", 最后登录: " . $zhjyUser->dawn_zhjyLastLoginTime;
                            }
                            if (isset($zhjyUser->dawn_zhjyDepartment)) {
                                $userInfo .= ", 部门: " . $zhjyUser->dawn_zhjyDepartment;
                            }
                        }
                        break;
                    }
                }
            } else {
                Log::warning('会话未设置，无法获取用户信息');
            }
        } catch (\Exception $e) {
            Log::error('获取用户信息失败: ' . $e->getMessage());
        }
        
        $ip = $request->ip();

        $formattedHeaders = "";
        foreach ($headers as $key => $values) {
            $formattedHeaders .= "  $key: " . implode(', ', $values) . "\n";
        }

        $logMessage = <<<EOT
------------------------ HTTP 请求信息 ------------------------
请求时间: $requestTime
请求方法: $method
请求地址: $url
请求用户: $userInfo
请求IP: $ip
User-Agent: $userAgent
请求参数: $body
请求头:
$formattedHeaders
--------------------------------------------------------------
EOT;

        Log::info($logMessage);
    }

    private function logResponse($response)
    {
        $endTime = microtime(true);
        $duration = round(($endTime - $this->startTime) * 1000, 2); // 转换为毫秒并保留两位小数
        
        $statusCode = $response->getStatusCode();
        $content = $response->getContent();

        $logMessage = <<<EOT
------------------------ HTTP 响应信息 -----------------------
状态码: $statusCode
处理时间: {$duration}毫秒
响应内容:
$content
--------------------------------------------------------------
EOT;

        Log::info($logMessage);
    }
}